package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    OrderMapper orderMapper;

    @Override

    public void submit(Orders orders) {
        // orders  order_detail
        // 0、获取用户id
        Long userId = BaseContext.getCurrentId();
        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        //拿到地址数据因为不只有一个地址
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(qw);
        // 2、查询用户数据 select * from user where id = ? 根据userid拿到user对象
        User user = userMapper.selectById(userId);
        // 3、根据地址id查询地址数据 select * from address_book where id = ? 根据传过来的orders的addressbookId拿到地址对象
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        //订单号
        long orderId = IdWorker.getId();
        //总价 用来接收放入设置的价格总价
        BigDecimal amount = new BigDecimal(0);
        //遍历地址集合
        for (ShoppingCart shoppingCart : shoppingCarts) {
            //创建一个订单详情对象
            OrderDetail orderDetail = new OrderDetail();
            //把购物车对象拷贝到订单详情对象
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orderId);
            //拿到数量准备做运算
            /*BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());*/
            //订单表的价格*订单表的数量
            orderDetail.setAmount(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));
            //把总价放入
            amount = amount.add(orderDetail.getAmount());
            //把设置好的数据保存到数据库
            orderDetailMapper.insert(orderDetail);
        }
        // 5、保存订单数据，有许多数据需要单独设置
        orders.setId(orderId);
        //2正在派送
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);
        orders.setAmount(amount);
        orders.setUserId(userId);
        //订单号
        orders.setNumber(String.valueOf(orderId));
        String name = user.getName();
        orders.setUserName(name);
        String consignee = addressBook.getConsignee();
        orders.setConsignee(consignee);//收货人
        String phone = addressBook.getPhone();
        orders.setPhone(phone);
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        orderMapper.insert(orders);
        // 6、删除当前用户的购物车数据
        // delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(qw2);
    }
}
